package velox.jcr.mapper.declarative;

import java.util.List;
import java.util.Map;

import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.springframework.beans.BeanWrapper;
import org.springframework.util.Assert;

import testmodel.OrderLine;
import velox.jcr.mapper.CascadeType;
import velox.jcr.mapper.CollectionPersister;
import velox.jcr.mapper.LazyList;
import velox.jcr.mapper.Loader;
import velox.jcr.mapper.Mapper;
import velox.jcr.mapper.UnitOfWorkHolder;

public class DescendantsMapping implements Mapping {

	private String javaProperty;
	private Class<?> type;
	private Loader<List<String>> loader;
	private CascadeType cascade;
	private String containerName;

	public DescendantsMapping(String javaProperty, String containerName, Class<?> type,
			Loader<List<String>> loader, CascadeType cascade) {
		this.containerName = containerName;
		this.javaProperty = javaProperty;
		this.type = type;
		this.loader = loader;
		this.cascade = cascade;
		Assert.isTrue(cascade.isRemove());
	}

	public void setCascade(CascadeType cascade) {
		this.cascade = cascade;
		Assert.isTrue(cascade.isRemove());
	}
	
	public void setType(Class<?> type) {
		this.type = type;
	}
	
	public void setLoader(Loader<List<String>> loader) {
		this.loader = loader;
	}
	
	public void setJavaProperty(String javaProperty) {
		this.javaProperty = javaProperty;
	}
	
	public String getJavaProperty() {
		return javaProperty;
	}
	
	public void read(Node node, BeanWrapper destination)
			throws RepositoryException {
		destination.setPropertyValue(javaProperty, 
				new LazyList<OrderLine>(node.getUUID(), loader, type));
	}

	public void readFromCache(Map<String, Object> cache, BeanWrapper destination) {
		destination.setPropertyValue(javaProperty, 
				new LazyList<OrderLine>(((String[]) cache.get(IdMapping.CACHE_KEY))[0], loader, type));
	}

	public void write(Node node, BeanWrapper object, boolean create) throws RepositoryException {
		Mapper mapper = UnitOfWorkHolder.get().getMapperManager().getMapper(type, null);
		CollectionPersister.writeCollection(
				(List<?>) object.getPropertyValue(javaProperty), node, create, containerName, cascade, mapper);
	}

	public void writeToCache(Map<String, Object> cache, BeanWrapper object) {
	}

}
